package paqueteeclipseserie;

import gnu.io.*;
/*
 import gnu.io.CommPort;
 import gnu.io.CommPortIdentifier;
 import gnu.io.PortInUseException;
 import gnu.io.SerialPort;
 */
import java.util.*;

import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import java.awt.Color;
//import java.util.HashSet;


public class TwoWaySerialComm 
{
	public TwoWaySerialComm()
	{
		super();

	}

	// PUERTO QUE SE VA A ABRIR
	private static final String PORT_NAMES[] = { "/dev/ttyUSB0",
			"/dev/ttyUSB1", "/dev/ttyUSB2", "/dev/ttyUSB3", };
	
	static OutputStream       outputStream;
   // static String	      messageString = "ON01";
    
    static SerialPort  PUERTOCERRAR;
    static SerialPort  serialPort;
    
    static Enumeration	      portList;
    static CommPortIdentifier portId;
    
	static String defaultPort = "/dev/ttyUSB1";//5

	void connect(String portName) throws Exception
	{
		CommPortIdentifier portIdentifier = CommPortIdentifier
				.getPortIdentifier(portName);
		if (portIdentifier.isCurrentlyOwned())
		{
			System.out.println("Error: Port is currently in use");
		} else
		{
			CommPort commPort = portIdentifier.open(this.getClass().getName(),
					2000);
						
			if (commPort instanceof SerialPort)
			{
				//SerialPort serialPort = (SerialPort) commPort;
				serialPort = (SerialPort) commPort;
				/*serialPort = 
					    (SerialPort) portIdentifier.open("SimpleWrite", 2000);//*/
				 
				
				try {
						outputStream = serialPort.getOutputStream();
					    } catch (IOException e) {}
				
				serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
						SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

				InputStream in = serialPort.getInputStream();
				OutputStream out = serialPort.getOutputStream();

				//(new Thread(new SerialReader(in))).start();
				//(new Thread(new SerialWriter(out))).start();
				
				try 
			    {
			    	serialPort.notifyOnOutputEmpty(true);
			    } catch (Exception e) {
				System.out.println("Error setting event notification");
				System.out.println(e.toString());
				System.exit(-1);
			    }
				
			} else
			{
				System.out
						.println("Error: Only serial ports are handled by this example.");
			}
		}
	}

	/** LECTURA DE LO QUE ENTRA AL PUERTO USB */
/*
	public static class SerialReader implements Runnable
	{
		InputStream in;

		public SerialReader(InputStream in)
		{
			this.in = in;
		}

		public void run()
		{
			byte[] buffer = new byte[1024];
			int len = -1;
			try
			{
				while ((len = this.in.read(buffer)) > -1)
				{
					System.out.print(new String(buffer, 0, len));
				}
			} catch (IOException e)
			{
				e.printStackTrace();
			}
		}
	}
//*/
	/** ESCRITURA EN EL PUERTO USB */
	/*
	public static class SerialWriter implements Runnable
	{
		OutputStream out;

		public SerialWriter(OutputStream out)
		{
			this.out = out;
		}

		public void run()
		{
			try
			{
				int c = 0;
				while ((c = System.in.read()) > -1)
				{
					this.out.write(c);
				}
			} catch (IOException e)
			{
				e.printStackTrace();
			}
		}
	}//*/
	/** Funcion que escribe una cadena en el puerto
	 * 
	 * 
	 */
	public static void EscribirPuerto( String messageString)
	{
		try
		{
			System.out.println("Escribir");
			outputStream.write(messageString.getBytes());
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
/**
 * cierra el puerto 
 * 
 * @param portName
 * @throws Exception
 */
	public static void CerrarPuerto(String portName) throws Exception
	{
		portList = CommPortIdentifier.getPortIdentifiers();

		while (portList.hasMoreElements()) {
		    portId = (CommPortIdentifier) portList.nextElement();

		    if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) 
		    {

			if (portId.getName().equals(defaultPort))
			{
			    System.out.println("Found port " + defaultPort);
			    //portFound = true;
			    try 
			    {
				PUERTOCERRAR = 
				    (SerialPort) portId.open("SimpleWrite", 2000);
			    } catch (PortInUseException e) 
			    {
				System.out.println("Port in use.");
				continue;
			    } 
//*/
			    try {
				outputStream = PUERTOCERRAR.getOutputStream();
			    } catch (IOException e) {}

/*			    try 
			    {
			    	PUERTOCERRAR.setSerialPortParams(9600, 
							       SerialPort.DATABITS_8, 
							       SerialPort.STOPBITS_1, 
							       SerialPort.PARITY_NONE);
			    } catch (UnsupportedCommOperationException e) {}
		
//*/
			    try 
			    {
			    	PUERTOCERRAR.notifyOnOutputEmpty(true);
			    } catch (Exception e) {
				System.out.println("Error setting event notification");
				System.out.println(e.toString());
				System.exit(-1);
			    }
			   // System.out.println("Writing \""+messageString+"\" to "+serialPort.getName());

	/*		    try {
//			    System.out.println("Writing \""+messageString+"\" to "+serialPort.getName());
				outputStream.write(messageString.getBytes());
			    } catch (IOException e) {}
//*/
			    try {
			       Thread.sleep(2000);  // Be sure data is xferred before closing
			    } catch (Exception e) {}
			    PUERTOCERRAR.close();
			    System.exit(1);
			} 
		    } 
		}
		
		
	}
	
	/**
	 * Main de ejecucion
	 * @throws InterruptedException 
	 * */
	public static void main(String[] args) throws InterruptedException
	{
		//
		TwoWaySerialComm main = new TwoWaySerialComm();
		
	//	getAvailableSerialPorts(); 

		/** TRATA DE INICIALIZAR EL PUERTO */
	
	/*	try
		{
			main.connect(defaultPort);
			//(new TwoWaySerialComm()).connect(defaultPort);
		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		
		}// */
		
		try
		{
			TwoWaySerialComm.CerrarPuerto(defaultPort);
		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//		System.out.println("ANTES DE SALIR");
		//main.EscribirPuerto("ON01");
//		serialPort.close();
//		System.exit(1);

	}

	/**
	 * @return A HashSet containing the CommPortIdentifier for all serial ports
	 *         that are not currently being used.
	 */
	public static HashSet<CommPortIdentifier> getAvailableSerialPorts()
	{
		HashSet<CommPortIdentifier> h = new HashSet<CommPortIdentifier>();
		Enumeration thePorts = CommPortIdentifier.getPortIdentifiers();
		// System.out.println("Puertos Encontrados");
		// int i=0;
		while (thePorts.hasMoreElements())
		{
			CommPortIdentifier com = (CommPortIdentifier) thePorts
					.nextElement();

			for (String portName : PORT_NAMES)
			{

				if (com.getName().equals(portName))
				// if(PORT_NAMES[i] == Puerto)
				{	
					defaultPort = com.getName();
					System.out.println("puerto seleccionado " + defaultPort);
				}

			}

		
		}
		return h;  //verificar si no esta de mas!
		
	}
		
}